package com.fla.puzzle.utils;

import com.fla.puzzle.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;

public class AndroidUtils {
    private static final String MARKET_TEMPLATE = "market://details?id=%s";
    private static final String GET_MORE = "market://search?q=%s";

    public static void playSound(Context context, int rawId) {
        MediaPlayer mp = MediaPlayer.create(context, rawId);
        if (mp != null) {
            mp.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
            mp.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                }
            });
            mp.start();
        }
    }

    public static void launchGooglePlay(Context context) {
        Intent playStoreIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(MARKET_TEMPLATE,
            context.getApplicationInfo().packageName)));
        context.startActivity(playStoreIntent);
    }

    public static void contactDeveloper(Context context) {
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setType("plain/text");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"yahor.makouski@gmail.com"});
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.app_name) + getDeviceInfo(context));
        context.startActivity(Intent.createChooser(emailIntent, "Mail app"));
    }

    public static void getMore(Context context, String keyword) {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(GET_MORE, keyword)));
        context.startActivity(browserIntent);
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Activity.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
        return metrics;
    }

    public static int dpToPx(Resources resources, int dp) {
        DisplayMetrics d = resources.getDisplayMetrics();
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, d);
    }

    public static void safeDismiss(Dialog progressDialog) {
        try {
            // when dialog is already dismissed we get IllegalArgumentException: View not attached to window manager
            // this is not "Death" exception
            progressDialog.dismiss();
        }
        catch (IllegalArgumentException e) {
            Log.e("AndroidUtils", "Cannot dismiss dialog", e);
        }
    }

    public static boolean showWhatsNewIfNecessary(Context context, final OnCancelListener onCancelListener) {
        try {
            int versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;

            String whatsNewKey = "whats_new_shown_" + versionCode;
            String resourceKey = "whats_new_" + versionCode;
            String specificResourceKey = "whats_new_specific_" + versionCode;

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean whatsNewShown = preferences.getBoolean(whatsNewKey, false);

            int resourceId = context.getResources().getIdentifier(resourceKey, "string", context.getPackageName());
            int specResourceId = context.getResources().getIdentifier(specificResourceKey, "string", context.getPackageName());

            if (!whatsNewShown && (resourceId != 0 || specResourceId != 0)) {
                int messageId = specResourceId == 0 ? resourceId : specResourceId;

                new AlertDialog.Builder(context).setMessage(Html.fromHtml(context.getResources().getString(messageId)))
                    .setPositiveButton("Ok", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (onCancelListener != null) {
                                onCancelListener.onCancel(dialog);
                            }
                        }
                    }).setOnCancelListener(onCancelListener).create().show();

                preferences.edit().putBoolean(whatsNewKey, true).commit();

                return true;
            }
            return false;
        }
        catch (NameNotFoundException e) {
            throw new IllegalArgumentException("Unknown package name: " + context.getPackageName());
        }
    }

    private static String getDeviceInfo(Context context) {
        try {
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            return String.format(" (%s %s, app v. %s, android v. %s)", Build.MANUFACTURER, Build.MODEL, versionName,
                Build.VERSION.RELEASE);
        }
        catch (NameNotFoundException e) {
            throw new IllegalArgumentException("Unknown name", e);
        }
    }
}
